import { createVNode, reactive, ref, Ref,unref,onMounted } from 'vue';
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { post } from "@/request/useRequest";
import { deleted,post as indiPost } from "@/request/indicator-axios/useRequest";
import { VxeTableDefines } from "vxe-table/types/table";
import { Props } from '@/components/typing'
import { useGridUtil } from '@/components/grid/grid-util';

export type pageEvent = {
    $event: Event,
    $pager: any,
    currentPage: number,
    pageSize: number,
    type: string
}
export const useTableHook = () => {
    const usePage = (pageSize= 25) => {
        const usePageOptions = [10, 25, 30, 50,200]
        const page = reactive({
            currentPage: 1,
            pageSize: pageSize,
            totalResult: 0
        });
        const usePageChange = (event: pageEvent | undefined):Promise<void> => {
            return new Promise(resolve => {
                if(event) {
                    page.currentPage = event?.currentPage;
                    page.pageSize = event?.pageSize;
                }
                resolve()
            })
        }
        return {
            usePageOptions,
            page,
            usePageChange
        }
    }
    const actions = (offset = 0) => {
        const tableRef:Ref = ref<any>(null);
        const height = ref('')
        const useDeleteAll = (ids: string[] | number[] | Ref<string[]>  | Ref<number[]>, tableName: string, primaryKey= 'id',url?: string):Promise<boolean> => {
            return new Promise<boolean>((resolve, reject) => {
                ids = unref(ids);
                if(!ids || ids.length < 1) return
                Modal.confirm({
                    title: '数据删除',
                    icon: createVNode(ExclamationCircleOutlined),
                    content: '您确定要删除所选数据吗?',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk() {
                        url = url ? url : 'role/deleteAll'
                        post(url, ids,{ tableName,primaryKey }).then(res => {
                            if (res.success) {
                                message.success("删除成功");
                                resolve(true)
                            }
                        }).catch(err => reject(err))
                    }
                });
            })
        }
        const useDelete = (tableName: string, primaryKey= 'id',url?: string):Promise<boolean> => {
            const formInfos = tableRef.value.getCheckboxRecords();
            if(!formInfos || formInfos.length < 1) return new Promise(resolve => resolve(false))
            const ids:string[] | number[] = formInfos.map((item:any) => item.id);
            return useDeleteAll(ids,tableName,primaryKey,url)
        }
        const useFilter = (filterLike=true) => {
            const { isTrim } = useGridUtil()
            const map:Props = {};
            let filters:VxeTableDefines.FilterCheckedParams[] = []
            if(tableRef && tableRef.value) filters =  tableRef.value.getCheckedFilters()
            if(filters && filters.length > 0) {
                filters.forEach((item: Props) => {
                    if(item.values && item.values.length > 0) {
                        item.values = item.values.filter((value: any) => value !== undefined)
                        if(item.values && item.values.length > 0) {
                            if(filters[0].column.filterMultiple) {
                                map[`${item.property}s`] = item.values;
                            } else {
                                map[`${item.property}`] = item.values[0];
                            }
                        }
                    }
                    if(item.datas && item.datas.length > 0) {
                        if(item.datas[0]) {
                            if(typeof item.datas[0] === 'string' && filterLike) {
                                console.log('item.datas',item.datas)
                                if(isTrim(item.datas[0])) {
                                    map[`${item.property}Like`] = item.datas[0]?.trim();
                                } else {
                                    map[`${item.property}Like`] = item.datas[0];
                                }
                            } else {
                                map[item.property] = item.datas[0];
                            }
                        }
                    }
                })
            }
            return map
        }
        const useSort = () => {
            let sort = ''
            let sorts:any[] = []
            if(tableRef && tableRef.value) sorts = tableRef.value.getSortColumns()
            if(sorts && sorts.length > 0) {
                sort = `${sorts[0].property} ${sorts[0].order}`
            }
            return sort
        }
        const builderHeight = () => {
            if(!tableRef.value?.getParentElem()) return '640px'
            const children = tableRef.value.getParentElem().children

            let content = document.getElementsByClassName('ant-layout-content ant-pro-basicLayout-content ant-pro-basicLayout-has-header');
            if(!content || content.length < 1) return '640px'

            const totalHeight:number = (content[0] as HTMLElement).offsetHeight
            let otherHeight: number = 0
            otherHeight += parseInt(getComputedStyle(content[0], null)["paddingTop"])
            if(tableRef.value.getParentElem().className === 'ant-card-body') {
                const head = document.getElementsByClassName('ant-card-head');
                const bordered = document.getElementsByClassName('ant-card ant-card-bordered');
                if(head && head.length > 0) {
                    otherHeight += (head[0] as HTMLElement).offsetHeight
                    otherHeight += parseInt(getComputedStyle(tableRef.value.getParentElem(), null)["paddingTop"])
                    otherHeight += parseInt(getComputedStyle(tableRef.value.getParentElem(), null)["paddingBottom"])
                    otherHeight += parseInt(getComputedStyle(tableRef.value.getParentElem(), null)["marginTop"])
                    otherHeight += parseInt(getComputedStyle(tableRef.value.getParentElem(), null)["marginBottom"])
                }
                if(bordered && bordered.length > 0) {
                    otherHeight += parseInt(getComputedStyle(bordered[0], null)["border"])
                }
            }

            for(let i = 0; i < children.length; i++) {
                const item: HTMLElement = children[i];
                if((item.className as string) !== tableRef.value.$el.className) {
                    otherHeight += item.offsetHeight;
                }
            }
            otherHeight += offset
            height.value = (totalHeight - (otherHeight + 4)) + 'px'
        }
        const builderHeight2 = (heightValue: string,index: number) => {
            if(!tableRef.value?.getParentElem()) return heightValue
            const children = tableRef.value.getParentElem().children

            let content = document.getElementsByClassName('ant-card ant-card-bordered ant-card-small');
            if(!content || content.length < 1) return heightValue

            const totalHeight:number = (content[0] as HTMLElement).offsetHeight
            let otherHeight: number = 0
            otherHeight += parseInt(getComputedStyle(content[0], null)["paddingTop"])
            if(tableRef.value.getParentElem().className === 'ant-card-body') {
                const head = document.getElementsByClassName('ant-card-head');
                const bordered = document.getElementsByClassName('ant-card ant-card-bordered');
                if(head && head.length > 0) {
                    otherHeight += (head[0] as HTMLElement).offsetHeight
                    otherHeight += parseInt(getComputedStyle(tableRef.value.getParentElem(), null)["paddingTop"])
                    otherHeight += parseInt(getComputedStyle(tableRef.value.getParentElem(), null)["paddingBottom"])
                    otherHeight += parseInt(getComputedStyle(tableRef.value.getParentElem(), null)["marginTop"])
                    otherHeight += parseInt(getComputedStyle(tableRef.value.getParentElem(), null)["marginBottom"])
                }
                if(bordered && bordered.length > 0) {
                    otherHeight += parseInt(getComputedStyle(bordered[0], null)["border"])
                }
            }

            for(let i = 0; i < children.length; i++) {
                const item: HTMLElement = children[i];
                if((item.className as string) !== tableRef.value.$el.className) {
                    otherHeight += item.offsetHeight;
                }
            }
            return (totalHeight - (otherHeight + 4)) + 'px'
        }
        onMounted(() => {
            builderHeight()
        })

        //指标删除
        const useDeleteIndi = (url: string, value: string | object | [],primaryKey= 'id'):Promise<boolean> => {
            return new Promise<boolean>((resolve, reject) => {
                Modal.confirm({
                    title: '数据删除',
                    icon: createVNode(ExclamationCircleOutlined),
                    content: '您确定要删除所选数据吗?',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk() {
                        if(typeof value === 'object' || value.constructor == Array) {
                            indiPost(url,value,null).then(res => {
                                if (res.success) {
                                    message.success("成功");
                                    resolve(true)
                                }
                            }).catch(err => reject(err))
                        } else {
                            const params:Props = {}
                            params[primaryKey] = value
                            deleted(url,null,params).then(res => {
                                if (res.success) {
                                    message.success("成功");
                                    resolve(true)
                                }
                            }).catch(err => reject(err))
                        }
                    }
                });
            })
        }
        return {
            tableRef,
            useDeleteAll,
            useDelete,
            useFilter,
            useSort,
            height,
            builderHeight2,
            useDeleteIndi
        }
    }
    return {
        usePage,
        actions
    }
}
